package com.can.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.can.domain.entity.Role;
import com.can.domain.entity.RoleMenu;
import com.can.domain.vo.PageVO;
import com.can.mapper.RoleMapper;
import com.can.service.RoleMenuService;
import com.can.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息表(Role) 服务实现类
 *
 * @author cancan
 * @since 2023-05-11 10:33:33
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMenuService roleMenuService;

    @Override
    public List<String> selectRoleKeyByUserId(Long id) {
        //判断是否是管理员 如果是返回集合中只需要有admin
        if(id == 1L){
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }
        //否则查询用户所具有的角色信息
        return getBaseMapper().selectRoleKeyByUserId(id);
    }

    @Override
    public PageVO page(Integer pageNum, Integer pageSize, Role role) {
        Page result = new Page(pageNum, pageSize);
        page(result,new LambdaQueryWrapper<Role>()
                .like(StringUtils.hasText(role.getRoleName()),Role::getRoleName,role.getRoleName())
                .eq(StringUtils.hasText(role.getStatus()),Role::getStatus,role.getStatus())
                .orderByAsc(Role::getRoleSort)
        );
        return new PageVO(result.getRecords(), result.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Role role) {
        save(role);
        List<RoleMenu> collect = role.getMenuIds().stream().map(id -> new RoleMenu(role.getId(), id)).collect(Collectors.toList());
        roleMenuService.saveBatch(collect);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role role) {
        updateById(role);
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, role.getId()));
        List<RoleMenu> collect = role.getMenuIds().stream().map(menuId -> new RoleMenu(role.getId(), menuId)).collect(Collectors.toList());
        roleMenuService.saveBatch(collect);
    }

}

